package com.xiaobu.shop.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaobu.shop.domain.ResponseResult;
import com.xiaobu.shop.domain.dto.ShopUserDTO;
import com.xiaobu.shop.domain.entity.ShopUser;
import com.xiaobu.shop.domain.exception.ShopException;
import com.xiaobu.shop.domain.security.ShopUserDetails;
import com.xiaobu.shop.mapper.ShopUserMapper;
import com.xiaobu.shop.service.ShopUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobu.shop.util.BeanCopyUtils;
import com.xiaobu.shop.util.JwtUtil;
import com.xiaobu.shop.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaobu
 * @since 2023-06-16
 */
@Service
public class ShopUserServiceImpl extends ServiceImpl<ShopUserMapper, ShopUser> implements ShopUserService {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    RedisCache redisCache;

    @Autowired
    ShopUserMapper shopUserMapper;
    @Override
    public ResponseResult login(ShopUser shopUser) {
        //获取认证信息
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(shopUser.getUsercode(),shopUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (Objects.isNull(authenticate)){
            throw new ShopException("登录失败");
        }
        //获取id生成jwt
        ShopUser user = ((ShopUserDetails)authenticate.getPrincipal()).getUser();
        String id = user.getId().toString();
        String jwt = JwtUtil.createJWT(id);
        //将jwt用map存储放入redis
        redisCache.setCacheObject("login:"+id,user);

        Map<String,String> map=new HashMap<>();
        map.put("token",jwt);
        map.put("user",JSON.toJSONString(BeanCopyUtils.copyBean(user, ShopUserDTO.class)));


        return new ResponseResult(200,"登陆成功",map);
    }

    @Override
    public ResponseResult register(ShopUser shopUser) {
        String usercode = shopUser.getUsercode();
        LambdaQueryWrapper<ShopUser> wrapper=new LambdaQueryWrapper();
        wrapper.eq(ShopUser::getUsercode,usercode)
                .or()
                .eq(ShopUser::getEmail,shopUser.getEmail())
                .or()
                .eq(ShopUser::getPhone,shopUser.getPhone());
        List<ShopUser> list = shopUserMapper.selectList(wrapper);
        if (list.size()>0){
            throw new ShopException("账号/邮箱/手机已被注册");
        }
        String password = shopUser.getPassword();
        String encode = passwordEncoder.encode(password);
        shopUser.setPassword(encode);
        shopUserMapper.insert(shopUser);
        shopUser.setPassword(null);
        ResponseResult responseResult=new ResponseResult(200,"注册成功",shopUser);
        return responseResult;
    }
}
